'use strict';
const redis = require('redis');

const redisclient = {

    client: null,

    init: function () {
        if (!this.client) {
            this.connect();
        }
    },

    connect: function () {
        this.client = redis.createClient({
            host: '127.0.0.1',
            port: '6379',
            password: 'fafa.com.cn',
            retry_strategy: function (options) {
                if (options.error && options.error.code === 'ECONNREFUSED') {
                    return new Error('The server refused the connection');
                }
                if (options.total_retry_time > 1000 * 1 * 30) {
                    // End reconnecting after a specific timeout and flush all commands
                    // with a individual error
                    return new Error('timeout');
                }
                if (options.attempt > 10) {
                    // End reconnecting with built in error
                    return undefined;
                }
                // reconnect after
                return Math.min(options.attempt * 5, 3000);
            }
        });
    },

    get: function (key) {
        let rc = this;
        rc.init();
        return new Promise(function (resolve, reject) {
            if (rc.client) {
                rc.client.hgetall(key, function (err, reply) {
                    console.log('redis result', err, '=====================', reply);
                    if (err) {
                        reject(null);
                    } else {
                        resolve({
                            ResultCode: '0', ResultValue: [{
                                errMsg: {
                                    List: [reply]
                                }
                            }]
                        });
                    }
                });
            } else {
                reject(null);
            }
        });
    },

    set: function (key, value) {
        console.log('will set key', key, value);
        if (this.client) {
            this.client.hmset(key, value);
        } else {
            console.error('no redis client for set')
        }
    },

    del: function (key, cb) {
        if (this.client) {
            this.client.del(key, cb);
        } else {
            console.error('no redis client for del')
        }
    }
};

module.exports = redisclient;